package com.example.library.controller;

import com.example.library.entity.Admin;
import com.example.library.entity.ApiResponse;
import com.example.library.entity.User;
import com.example.library.mapper.UserMapper;
import com.example.library.service.IAdminService;

import com.example.library.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sx
 * @since 2024-12-17
 */
@RestController
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") // 替换为你的前端地址
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

//    //管理员登录，登录成功返回管理员的信息，否则返回错误信息
//    @PostMapping("/login")
//    public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password) {
//        try {
//            Admin admin = adminService.login(username, password);
//            if (admin != null) {
//                return ResponseEntity.ok(admin);
//            } else {
//                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
//            }
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error logging in: " + e.getMessage());
//        }
//    }
    /**
     * 获取当前登录管理员的个人信息
     * @return 当前登录管理员的信息
     */
    @GetMapping("/admin/profile")
    public ResponseEntity<?> getProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        ;
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("No admin is currently logged in");
        }

        // 从认证对象中获取用户名
        Object principal = authentication.getPrincipal();
        String name;

        if (principal instanceof UserDetails) {
            name = ((UserDetails) principal).getUsername();
        } else {
            name = principal.toString();
        }

        Admin admin = adminService.getAdminByName(name);
        if(admin != null){
            return  ResponseEntity.ok(admin);
        }
        else{
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("No admin found for the current session");
        }

    }

//    /**
//     * 更新当前登录管理员的个人信息
//     * @param updatedAdmin 更新后的管理员信息
//     * @return 更新后的管理员信息
//     */
//    @PutMapping("/admin/update")
//    public ResponseEntity<?> updateProfile(@RequestBody Admin updatedAdmin) {
//        try {
//            // 获取当前登录用户信息
//            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//            if (authentication == null || !authentication.isAuthenticated()) {
//                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("No admin is currently logged in");
//            }
//
//            Object principal = authentication.getPrincipal();
//            String name;
//
//            if (principal instanceof UserDetails) {
//                name = ((UserDetails) principal).getUsername();
//            } else {
//                name = principal.toString();
//            }
//
//            // 根据用户名更新管理员信息
//            updatedAdmin.setName(name);
//            Admin updated = adminService.updateProfile(updatedAdmin);
//
//            return ResponseEntity.ok(updated);
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error updating admin profile: " + e.getMessage());
//        }
//    }
//
//    @PutMapping("/saveOrUpdate")
//    public boolean saveOrUpdate(@RequestBody Admin admin){
//        return adminService.saveOrUpdate(admin);
//    }

    //获取所有的管理者
    @GetMapping("/admin/list")
    public List<Admin> remove(){
        return adminService.list();
    }


    //获取所有的用户信息
    @GetMapping("/userlist")
    @CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") // 替换为你的前端地址
    public List<User> userList(){
        return userService.list();
    }

    @PostMapping("/useradd")
    @ResponseBody
    public ResponseEntity<User> addUser(@RequestBody User user){
        int result = userMapper.insert(user);
        if(result != 0){
            ApiResponse response = new ApiResponse("success", "读者添加成功",user);
            return new ResponseEntity<>(user, HttpStatus.OK);
        }
        else{
            ApiResponse response = new ApiResponse("error", "用户类别失败", null);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
